package com.agileai.portal.controller.wcm;

import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.TreeManageHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.portal.bizmoduler.wcm.KeyWordsTreeManage;
import com.agileai.util.StringUtil;

public class KeyWordsTreeManageHandler
        extends TreeManageHandler {
    public KeyWordsTreeManageHandler() {
        super();
        this.serviceId = buildServiceId(KeyWordsTreeManage.class);
        this.nodeIdField = "WORD_ID";
        this.nodePIdField = "WORD_PID";
        this.moveUpErrorMsg = "该节点是第一个节点，不能上移！";
        this.moveDownErrorMsg = "该节点是最后一个节点，不能下移！";
        this.deleteErrorMsg = "该节点还有子节点，不能删除！";
    }

    protected TreeBuilder provideTreeBuilder(DataParam param) {
        KeyWordsTreeManage service = this.getService();
        List<DataRow> menuRecords = service.findTreeRecords(param);
        TreeBuilder treeBuilder = new TreeBuilder(menuRecords, "WORD_ID",
                                                  "WORD_NAME", "WORD_PID");

        return treeBuilder;
    }

    protected void processPageAttributes(DataParam param) {
        setAttribute("WORD_ENABLED",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getAttributeValue("WORD_ENABLED")));
        setAttribute("CHILD_WORD_ENABLED",
                     FormSelectFactory.create("BOOL_DEFINE")
                                      .addSelectedValue(getAttributeValue("CHILD_WORD_ENABLED",
                                                                          "Y")));
    }

    protected String provideDefaultNodeId(DataParam param) {
        return "00000000-0000-0000-00000000000000000";
    }

    protected boolean isRootNode(DataParam param) {
        boolean result = true;
        String nodeId = param.get(this.nodeIdField,
                                  this.provideDefaultNodeId(param));
        DataParam queryParam = new DataParam(this.nodeIdField, nodeId);
        DataRow row = this.getService().queryCurrentRecord(queryParam);

        if (row == null) {
            result = false;
        } else {
            String parentId = row.stringValue("WORD_PID");
            result = StringUtil.isNullOrEmpty(parentId);
        }

        return result;
    }

    protected KeyWordsTreeManage getService() {
        return (KeyWordsTreeManage) this.lookupService(this.getServiceId());
    }
}
